
//
//  CYStatusListViewModel.swift
//  WeiBo
//
//  Created by Mr_J on 16/3/9.
//  Copyright © 2016年 mac. All rights reserved.
//

import UIKit
import SDWebImage

class CYStatusListViewModel: NSObject {
    
    var statusArray: [CYStatusViewModel]?
    
    //https://api.weibo.com/2/statuses/friends_timeline.json
    
    func loadData(isPullUp: Bool ,finished: (isSuccess: Bool)->()){
        
        var maxId: Int64 = 0
        
        var sinceId: Int64 = 0
        
        if isPullUp {
            maxId = statusArray?.last?.status?.id ?? 0
            if maxId != 0{
                maxId--
            }
        }else {
            sinceId = statusArray?.first?.status?.id ?? 0
        }
        
        let url = "https://api.weibo.com/2/statuses/friends_timeline.json"
        
        let parameters = ["access_token": CYUserAccountViewModel.sharedAccountViewModel.accessToken!,"max_id":"\(maxId)","since_id":"\(sinceId)"]
        
        CYNetworkTools.sharedTools.requst(.GET, urlString: url, parameters: parameters) { (responseObject, error) -> () in
            
            if error != nil {
                //                print("\(error)")
                finished(isSuccess: false)
                return
            }
            
//            print(responseObject)
            
            let dicts = responseObject!["statuses"] as! [[String : AnyObject]]
            
            var tempArray = [CYStatusViewModel]()
            
            for dict in dicts {
                
                let status = CYStatus(dict: dict)
                
//                if status.retweeted_status != nil {
//                    print("呵呵")
//                }
                
                let viewModel = CYStatusViewModel(status: status)
                
                tempArray.append(viewModel)
            }
            
            if self.statusArray == nil {
                self.statusArray = [CYStatusViewModel]()
            }
            
            if isPullUp {
                self.statusArray! = self.statusArray! + tempArray
            }else {
                self.statusArray! = tempArray + self.statusArray!
            }
            
            
           
            self.cacheSingleImage(tempArray, finished: finished)
            
//            finished(isSuccess: true)
        }
    }
    
    private func cacheSingleImage(viewModels: [CYStatusViewModel], finished: (isSeccess:Bool)->()) {
        
        let group = dispatch_group_create()
        
        let queue = dispatch_get_main_queue()
        
        for viewModel in viewModels {
            
            var urls = viewModel.status?.pic_urls
            
            if urls == nil || urls?.count == 0 {
                
                urls = viewModel.status?.retweeted_status?.pic_urls
                
            }
            
            if urls?.count == 1 {
                guard let urlString = urls?.first?.thumbnail_pic else {
                    continue
                }
                dispatch_group_enter(group)
                
                SDWebImageManager.sharedManager().downloadImageWithURL(NSURL(string: urlString), options: [], progress: nil, completed: { (image, error, _, _, url) -> Void in
                    
                    dispatch_group_leave(group)
                    
                })
            }
            
        }
        
        dispatch_group_notify(group, queue) { () -> Void in
            finished(isSeccess: true)
        }
        
    }

}
